package com.xinshujia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinshujia.dao.ThresholdDao;
import com.xinshujia.entity.ThresholdEntity;
import com.xinshujia.service.FunctionService;
import com.xinshujia.service.ThresholdService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-08-06 18:15       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 */
@Service
public class ThresholdServiceImpl extends ServiceImpl<ThresholdDao, ThresholdEntity> implements ThresholdService {
    private final ThresholdDao thresholdDao;
    private final FunctionService functionService;

    public ThresholdServiceImpl(ThresholdDao thresholdDao, FunctionService functionService) {
        this.thresholdDao = thresholdDao;
        this.functionService = functionService;
    }

    /**
     * 设置或更新阈值
     *
     * @param thresholdEntity 阈值实体
     * @return Boolean
     */
    @Transactional
    @Override
    public Boolean setOrUpdateThreshold(ThresholdEntity thresholdEntity) {
        // 设置阈值到硬件
        Boolean flag_hard = functionService.updateThreshold(thresholdEntity);
        // 设置或更新阈值数据库
        int insert = thresholdDao.insert(thresholdEntity);
        return flag_hard && insert > 0;
    }

    /**
     * 分页查询所有设备的当前阈值
     */
    @Override
    public Page<ThresholdEntity> findThresholdsByPage(Long pageNum, Long pageSize) {
        long offset = (pageNum - 1) * pageSize; // 计算偏移量
        List<ThresholdEntity> thresholdEntityList = thresholdDao.findThresholdsByPage(offset, pageSize);
        System.out.println(thresholdEntityList);
        Page<ThresholdEntity> pageList = new Page<>(pageNum, pageSize);
        pageList.setTotal(thresholdEntityList.size());
        pageList.setRecords(thresholdEntityList);
        return pageList;
    }

    /**
     * 根据deviceGuid查询该设备所有的阈值记录
     */
    @Override
    public Page<ThresholdEntity> findThresholdsByDeviceGuid(Long pageNum, Long pageSize, String deviceGuid) {
        if (!StringUtils.hasLength(deviceGuid)) return null;
        QueryWrapper<ThresholdEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_guid", deviceGuid);
        return thresholdDao.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }
}
